//
//  UIImageView+Cool.m
//  HX2Car
//
//  Created by Mudmen on 2017/8/11.
//  Copyright © 2017年 Hx2car_mac. All rights reserved.
//

#import "UIImageView+Cool.h"

@implementation UIImageView (Cool)

- (void)setImageColors:(NSArray *)colorArray gradientType:(GradientColorType)gradientColorType
{
    UIImage *image = [self imageFromColors:colorArray ByGradientType:gradientColorType];
    [self setImage:image];
}

- (UIImage *)imageFromColors:(NSArray *)colors ByGradientType:(GradientColorType)gradientColorType {
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(self.frame.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    switch (gradientColorType) {
        case GradientColorTypeTopToBottom:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(0.0, self.frame.size.height);
            break;
        case GradientColorTypeLeftToRight:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(self.frame.size.width, 0.0);
            break;
        case GradientColorTypeUpleftTolowRight:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(self.frame.size.width, self.frame.size.height);
            break;
        case GradientColorTypeUprightTolowLeft:
            start = CGPointMake(self.frame.size.width, 0.0);
            end = CGPointMake(0.0, self.frame.size.height);
            break;
        default:
            break;
    }
    
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

@end
